import axios, { type Method } from 'axios'
import { useUserStore } from './../stores/user'
import { showToast } from 'vant'
import router from '@/router'

// 1. 创建axios实例对象
const baseURL = 'https://consult-api.itheima.net'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 100000
})

// 2. 配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    // TODO2: 统一携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user?.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 3. 配置响应拦截器
instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data?.code !== 10000) {
      showToast(res.data?.message || '业务操作失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (error) => {
    // TODO 5. 处理401错误
    if (error.response.status === 401) {
      // 5.0 提示用户
      showToast('登录超时, 请重新登录')
      // 5.1 清除用户信息
      const store = useUserStore()
      store.delUser()
      // 5.2 跳转到登录页
      // /user?name=xxx&age=xxx
      // router.currentRoute.value.path ===>  /user
      // router.currentRoute.value.fullPath ===> /user?name=xxx&age=xxx
      router.replace({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath || '/user'
        }
      })
    }

    return Promise.reject(error)
  }
)

type Data<T> = {
  code: number
  message: string
  data: T
}

// 自己的request函数
const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  // axios里面的request函数
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE'
      ? 'params'
      : 'data']: submitData
  })
}

export { baseURL, request }
